import axios from 'axios'
import CacheApi from './cache'
import ConfigApi from './config'
import Qs from 'qs'
var baseUrl = process.env.NODE_ENV === 'production' ? ConfigApi.baseUrl : 'http://localhost:5000/'
// const Qs = require('qs')
function noEmpty(data) {
  const obj = Object.assign({}, data)
  Object.keys(obj).forEach((key) => {
    if (!obj[key] && obj[key] !== 0) delete obj[key]
  })
  return obj
}
class Http {
  constructor() {
    this.baseUrl = baseUrl
    axios.defaults.headers['Access-Control-Allow-Origin'] = '*'
    axios.defaults.headers['Access-Control-Allow-Methods'] = 'GET,POST,PUT'
    axios.defaults.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept'
    this.setToken(CacheApi.token)
    axios.interceptors.request.use(
      (config) => {
        return config
      },
      (err) => {
        return Promise.resolve(err)
      }
    )
    axios.interceptors.response.use(
      (res) => {
        if (res.status && res.status === 200 && res.data.status === 'error') {
          return
        }
        if (!res) return Promise.resolve(null)
        if (!res.status) return Promise.resolve(null)
        if (res.status === 200) return Promise.resolve(res.data)
        return Promise.resolve(null)
      },
      (err) => {
        if (!err || !err.response) return Promise.reject(err)
        let errMsg = ''
        if (err.response.status === 504 || err.response.status === 404) {
          errMsg = '服务器被吃了⊙﹏⊙∥'
        } else if (err.response.status === 401 || err.response.status === 403) {
          errMsg = '权限不足,请联系管理员!'
          localStorage.clear()
          alert(errMsg)
          document.location.href = '/#/login'
        } else if (err.response.status === 400) {
          errMsg = err.response.data || '请求信息有误'
        } else {
          errMsg = '网络异常,请稍后重试'
        }
        return Promise.reject(errMsg)
      }
    )
  }

  setToken = (token) => {
    axios.defaults.headers.token = token
  }

  POST = (url, data) => {
    this.setToken(CacheApi.token)
    const t = Object.prototype.toString.call(data).toString().slice(8, -1)
    if (t === 'Object') {
      data = noEmpty(data)
    }
    return axios.post(`${this.baseUrl}${url}`, data)
  }
  EXPORT = (url, data) => {
    this.setToken(CacheApi.token)
    const t = Object.prototype.toString.call(data).toString().slice(8, -1)
    if (t === 'Object') {
      data = noEmpty(data)
    }
    return axios.post(`${this.baseUrl}${url}`, data, { responseType: 'blob' })
  }
  DELETE = (url, data) => {
    this.setToken(CacheApi.token)
    return axios.delete(`${this.baseUrl}${url}`, { data: data })
  }

  DOWN = (url, data) => {
    this.setToken(CacheApi.token)
    return axios({ method: 'post', url: `${this.baseUrl}${url}`, responseType: 'arraybuffer', data: data })
  }

  POSTFILE = (url, data) => {
    this.setToken(CacheApi.token)
    var formData = new FormData()
    for (const k in data) {
      if (data[k]) {
        formData.append(k, data[k])
      }
    }
    return axios.post(`${this.baseUrl}${url}`, formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })
  }

  GET = (url, data) => {
    this.setToken(CacheApi.token)
    data = noEmpty(data)
    if (data && Object.keys(data).length > 0) {
      url = url + '?' + Qs.stringify(data, { allowDots: true })
    }
    return axios.get(`${this.baseUrl}${url}`)
  }

  WebGet = (url, data) => {
    if (data && Object.keys(data).length > 0) {
      url = url + '?' + Qs.stringify(data, { allowDots: true })
    }
    return axios.get(url)
  }

  WebPost = (url, data) => {
    return axios.post(url, data)
  }
  F = (path) => ({ GET: (url, data) => this.GET(`${path}${url}`, data), POST: (url, data) => this.POST(`${path}${url}`, data) })
}
const instance = new Http()
export default instance
export function F(path) {
  return { GET: (url, data) => instance.GET(`${path}${url}`, data), POST: (url, data) => instance.POST(`${path}${url}`, data),EXPORT:(url, data) => instance.EXPORT(`${path}${url}`, data) }
}
export const GET=instance.GET
export const POST=instance.POST